package com.oo.app.ui.im.activity;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.oo.app.R;
import com.oo.app.base.activities.BaseFragmentActivity;
import com.oo.app.ui.im.view.CustomPrivateConversationProvider;
import com.oo.app.ui.main.adapter.ConversationListAdapterEx;
import com.oo.app.ui.main.adapter.OldConversationListAdapter;
import com.oo.app.ui.im.fragment.MyConversationListFragment;
import com.oo.app.ui.im.fragment.OldConversationListFragment;
import com.oo.app.ui.view.CustomViewPager;
import com.oo.app.utils.AccountHelper;
import com.oo.app.widget.toast.Prompt;
import com.oo.app.widget.toast.SnackbarToast;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bingoogolapple.bgabanner.BGABanner;
import io.rong.common.RLog;
import io.rong.imkit.RongContext;
import io.rong.imkit.RongIM;
import io.rong.imkit.fragment.ConversationListFragment;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.UserInfo;

/**
 * @创建者 喻亚龙
 * @描述
 */

public class MessageActivity extends BaseFragmentActivity implements ViewPager.OnPageChangeListener,
        View.OnClickListener , RongIM.UserInfoProvider{

    @BindView(R.id.banner_guide_content)
    BGABanner banner;

    @BindView(R.id.tv_message_my)
    TextView tv_message_my;

    @BindView(R.id.tv_message_old)
    TextView tv_message_old;

    @BindView(R.id.line_message_my)
    View line_message_my;

    @BindView(R.id.line_message_old)
    View line_message_old;

    @BindView(R.id.mes_viewpager)
    CustomViewPager mViewPager;

    private List<Fragment> mFragment = new ArrayList<>();
    /**
     * 我的聊天会话列表的fragment
     */
    private ConversationListFragment mConversationListFragment = null;
    /**
     * 聊过的人列表的fragment
     */
    private ConversationListFragment mConversationOldListFragment = null;
    private Context mContext;
    public String token;
    public RongIM.UserInfoProvider userInfoProvider;


    public static void show(Context context) {
        Intent intent = new Intent(context, MessageActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int getContentView() {
        return R.layout.activity_message;
    }


    @Override
    protected void initWidget() {
        super.initWidget();
        mContext = this;
        changeTextViewColor();
        changeSelectedTabState(0);
        initMainViewPager();


//        RongIM.getInstance().registerConversationTemplate(new CustomPrivateConversationProvider());

        RongIM.setUserInfoProvider(new RongIM.UserInfoProvider() {

            @Override
            public UserInfo getUserInfo(String userId) {
                //根据 userId 去你的用户系统里查询对应的用户信息返回给融云 SDK。

//                findUserInfo(userId);
                return null;
            }

        }, true);

        banner();

        token = "rk9Jb/JeS1TscWolnN55kqWnIba4y5mfBFfmsRdXCO+bGT77Ygy3cRqspxOChu2ppIwxz/7w256zMxYlRUjqcQ==";

        if (!TextUtils.isEmpty(token))
            connect(token);
        RongIM.setConnectionStatusListener(new MyConnectionStatusListener());
    }

    private void banner(){
        banner.setAdapter(new BGABanner.Adapter<ImageView, String>() {
            @Override
            public void fillBannerItem(BGABanner banner, ImageView itemView, @Nullable String model, int position) {
                Glide.with(mContext)
                        .load(model)
                        .into(itemView);
            }
        });
        banner.setData(Arrays.asList("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1522392952&di=a66d6b12d776241402ab3e4e5fc0e92d&imgtype=jpg&er=1&src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F0161995719b81b6ac7254fbc9c3c18.jpg", "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1521798231875&di=31083d8c0000715eca239d55cb2a9536&imgtype=0&src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F019a3159a6256ea8012028a978c287.jpg%402o.jpg", "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1521798231875&di=04396d134bd191bb4fdcd9c829d92d8e&imgtype=0&src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F011c635849568ca801219c772aa1a0.png"), null);

    }

    private void initMainViewPager() {
        Fragment conversationList = initConversationList();
        Fragment conversationOldList = initConversationOldList();

        mFragment.add(conversationList);
        mFragment.add(conversationOldList);
        FragmentPagerAdapter fragmentPagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return mFragment.get(position);
            }

            @Override
            public int getCount() {
                return mFragment.size();
            }
        };
        mViewPager.setAdapter(fragmentPagerAdapter);
        mViewPager.setOffscreenPageLimit(4);
        mViewPager.setOnPageChangeListener(this);
        initData();
    }



    private Fragment initConversationList() {
        if (mConversationListFragment == null) {
            ConversationListFragment listFragment = new MyConversationListFragment();
            listFragment.setAdapter(new ConversationListAdapterEx(RongContext.getInstance()));
            Uri uri = Uri.parse("rong://" + getApplicationInfo().packageName).buildUpon()
                        .appendPath("conversationlist")
                        .appendQueryParameter(Conversation.ConversationType.PRIVATE.getName(), "false") //设置私聊会话是否聚合显示
                        .appendQueryParameter(Conversation.ConversationType.GROUP.getName(), "false")//群组
                        .appendQueryParameter(Conversation.ConversationType.PUBLIC_SERVICE.getName(), "false")//公共服务号
                        .appendQueryParameter(Conversation.ConversationType.APP_PUBLIC_SERVICE.getName(), "false")//订阅号
                        .appendQueryParameter(Conversation.ConversationType.SYSTEM.getName(), "true")//系统
                        .appendQueryParameter(Conversation.ConversationType.DISCUSSION.getName(), "true")
                        .build();

            listFragment.setUri(uri);
            mConversationListFragment = listFragment;
            return listFragment;
        } else {
            return mConversationListFragment;
        }
    }

    private Fragment initConversationOldList() {
        if (mConversationOldListFragment == null) {
            ConversationListFragment listFragment = new OldConversationListFragment();
            listFragment.setAdapter(new OldConversationListAdapter(RongContext.getInstance()));
            Uri uri = Uri.parse("rong://" + getApplicationInfo().packageName).buildUpon()
                        .appendPath("conversationlist")
                        .appendQueryParameter(Conversation.ConversationType.PRIVATE.getName(), "false") //设置私聊会话是否聚合显示
                        .appendQueryParameter(Conversation.ConversationType.GROUP.getName(), "false")//群组
                        .appendQueryParameter(Conversation.ConversationType.PUBLIC_SERVICE.getName(), "false")//公共服务号
                        .appendQueryParameter(Conversation.ConversationType.APP_PUBLIC_SERVICE.getName(), "false")//订阅号
                        .appendQueryParameter(Conversation.ConversationType.SYSTEM.getName(), "false")//系统
                        .appendQueryParameter(Conversation.ConversationType.DISCUSSION.getName(), "true")
                        .build();

            listFragment.setUri(uri);
            mConversationOldListFragment = listFragment;
            return listFragment;
        } else {
            return mConversationOldListFragment;
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        changeTextViewColor();
        changeSelectedTabState(position);
    }

    private void changeTextViewColor() {
        tv_message_my.setTextColor(getResources().getColor(R.color.textColor));
        line_message_my.setBackgroundResource(R.color.white);
        tv_message_old.setTextColor(getResources().getColor(R.color.textColor));
        line_message_old.setBackgroundResource(R.color.white);
    }

    private void changeSelectedTabState(int position) {
        switch (position) {
            case 0:
                tv_message_my.setTextColor(getResources().getColor(R.color.theme_color));
                line_message_my.setBackgroundResource(R.color.theme_color);
                break;
            case 1:
                tv_message_old.setTextColor(getResources().getColor(R.color.theme_color));
                line_message_old.setBackgroundResource(R.color.theme_color);
                break;
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    long firstClick = 0;
    long secondClick = 0;


    @OnClick({R.id.iv_back,R.id.ll_message_my,R.id.ll_message_old})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.ll_message_my:
                if (mViewPager.getCurrentItem() == 0) {
                    if (firstClick == 0) {
                        firstClick = System.currentTimeMillis();
                    } else {
                        secondClick = System.currentTimeMillis();
                    }
                    RLog.i("MainActivity", "time = " + (secondClick - firstClick));
                    if (secondClick - firstClick > 0 && secondClick - firstClick <= 800) {
                        mConversationListFragment.focusUnreadItem();
                        firstClick = 0;
                        secondClick = 0;
                    } else if (firstClick != 0 && secondClick != 0) {
                        firstClick = 0;
                        secondClick = 0;
                    }
                }
                mViewPager.setCurrentItem(0, false);
                break;
            case R.id.ll_message_old:
                if (mViewPager.getCurrentItem() == 0) {
                    if (firstClick == 0) {
                        firstClick = System.currentTimeMillis();
                    } else {
                        secondClick = System.currentTimeMillis();
                    }
                    RLog.i("MainActivity", "time = " + (secondClick - firstClick));
                    if (secondClick - firstClick > 0 && secondClick - firstClick <= 800) {
                        mConversationListFragment.focusUnreadItem();
                        firstClick = 0;
                        secondClick = 0;
                    } else if (firstClick != 0 && secondClick != 0) {
                        firstClick = 0;
                        secondClick = 0;
                    }
                }
                mViewPager.setCurrentItem(1, false);
                break;
        }
    }


    protected void initData() {

        final Conversation.ConversationType[] conversationTypes = {
                Conversation.ConversationType.PRIVATE,
                Conversation.ConversationType.GROUP, Conversation.ConversationType.SYSTEM,
                Conversation.ConversationType.PUBLIC_SERVICE, Conversation.ConversationType.APP_PUBLIC_SERVICE
        };

//        RongIM.getInstance().addUnReadMessageCountChangedObserver(MainActivity.this, conversationTypes);
    }

    @Override
    protected void onResume() {
        super.onResume();
//        final String token = PreferencesUtil.getToken(this);
//        if (!StringUtil.isEmpty(token))
//            connect(token);
        RongIM.setConnectionStatusListener(new MyConnectionStatusListener());
    }


    private class MyConnectionStatusListener implements RongIMClient.ConnectionStatusListener {

        @Override
        public void onChanged(ConnectionStatus connectionStatus) {

            switch (connectionStatus){

                case CONNECTED://连接成功。
//                    SimplexToast.show(mContext,"连接成功");
//                    SnackbarToast.make(mContext, "连接成功", 3000l)
//                            .setPromptThemBackground(Prompt.ERROR)
//                            .show();
                    break;
                case DISCONNECTED://断开连接。
                    if (!TextUtils.isEmpty(token))
                        connect(token);
                    break;
                case CONNECTING://连接中。

                    break;
                case NETWORK_UNAVAILABLE://网络不可用。
                    SnackbarToast.make(mContext, "网络不可用", 3000l)
                            .setPromptThemBackground(Prompt.ERROR)
                            .show();
                    break;
                case KICKED_OFFLINE_BY_OTHER_CLIENT://用户账户在其他设备登录，本机会被踢掉线
                    SnackbarToast.make(mContext, "用户账户在其他设备登录，本机会被踢掉线", 3000l)
                            .setPromptThemBackground(Prompt.ERROR)
                            .show();
                    break;
            }
        }
    }

    /**
     //     * 建立与融云服务器的连接
     //     *
     //     * @param token
     //     */
    private void connect(final String token) {

        if (!RongIM.getInstance().getCurrentConnectionStatus().equals(RongIMClient.ConnectionStatusListener.ConnectionStatus.CONNECTED)) {
            /**
             * IMKit SDK调用第二步,建立与服务器的连接
             */
            RongIM.connect(token, new RongIMClient.ConnectCallback() {
                /**
                 * Token 错误，在线上环境下主要是因为 Token 已经过期，您需要向 App Server 重新请求一个新的 Token
                 */
                @Override
                public void onTokenIncorrect() {
                    Log.e("Rong", "--onTokenIncorrect");
                }

                /**
                 * 连接融云成功
                 * @param userid 当前 token
                 */
                @Override
                public void onSuccess(String userid) {
                    Log.e("Rong", "--onSuccess---" + userid);
                    // 1
                    if(RongIM.getInstance() != null)
                        RongIM.getInstance().setCurrentUserInfo(new io.rong.imlib.model.UserInfo(userid, AccountHelper.getUser().getName(),
                                Uri.parse(AccountHelper.getUser().getIcon()))
                        );
                    // 2
                    RongIM.getInstance().setMessageAttachedUserInfo(true);

//                    io.rong.callkit.huke.Bean.UserInfo userCall = new io.rong.callkit.huke.Bean.UserInfo();
//                    userCall.setAge(AccountHelper.getUser().getAge());
//                    userCall.setSex(AccountHelper.getUser().getSex());
//                    userCall.setPosition(AccountHelper.getUser().getPosition());
//                    userCall.setIcon(AccountHelper.getUser().getIcon());
//                    userCall.setNickname(AccountHelper.getUser().getNickname());
//                    userCall.setFollow(AccountHelper.getUser().getFollow());
//                    userCall.setAccount_earning(AccountHelper.getUser().getAccount_earning());
//                    userCall.setCall_price(AccountHelper.getUser().getCall_price());
//                    RongCallKit.saveUser(mContext, token, userCall);
                }

                /**
                 * 连接融云失败
                 * @param errorCode 错误码，可到官网 查看错误码对应的注释
                 */
                @Override
                public void onError(RongIMClient.ErrorCode errorCode) {
                    Log.e("Rong","--onError" + errorCode);
                    Toast.makeText(MessageActivity.this, "与服务器失联", Toast.LENGTH_SHORT).show();
                }
            });
        }

    }

    @Override
    public UserInfo getUserInfo(String userId) {
//        findUserInfo(userId);

        return null;
    }





}
